/*
 * BanBu_GoLoginViewController
 * @description 本文件提供登录界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供登录界面的ViewController
 */


#import "BanBu_GoLoginViewController.h"
#import "TKLoadingView.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_LocationManager.h"
#import "UIDevice+Helper.h"
#import "BanBu_UpgradeDataBase.h"
#import "SFHFKeychainUtils.h"
#import "BanBu_ForgetPWController.h"
#import "QVerifyWebViewController.h"


@interface BanBu_GoLoginViewController ()

@end

@implementation BanBu_GoLoginViewController
#define TABLECOLOR [UIColor colorWithRed:0.840 green:0.336 blue:0.723 alpha:1.000]

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"登录", nil);
    
    //2014年10月13日17:35:04 by yinlinlin 清除缓存按钮
    UIView * footerV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 83)];
    footerV.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = footerV;
    [footerV release];
    
    //清除缓存按钮
    _clearBu = [UIButton buttonWithType:UIButtonTypeCustom];
    NSString * fileName = [[NSBundle mainBundle] pathForResource:@"clearCacheImg" ofType:@"png"];
    [_clearBu setBackgroundImage:[UIImage imageWithContentsOfFile:fileName] forState:UIControlStateNormal];
    [_clearBu setFrame:CGRectMake(170, 38, 150, 44)];
    [footerV addSubview:_clearBu];
    
    UILabel * comLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 140, 34)];
    comLabel.text = NSLocalizedString(@"clearIdPwd", nil);
    comLabel.backgroundColor = [UIColor clearColor];
    comLabel.font = [UIFont boldSystemFontOfSize:20.0];
    comLabel.textColor = UIColorWithRGB(8, 134, 228, 1.0);
    comLabel.textAlignment = kTextAlignmentCenter;
    [_clearBu addSubview:comLabel];
    [comLabel release];
    [_clearBu addTarget:self action:@selector(clearIdPasswordCache) forControlEvents:UIControlEventTouchUpInside];
    
	// Do any additional setup after loading the view.
}

#pragma mark - 清除用户id和密码缓存
/**
 * @函数名称：clearIdPasswordCache
 * @函数描述：清除本地记录的id密码缓存
 * @输入参数：nil
 * @输出参数：nil
 * @返回值：void
 * @author：yinlinlin
 */
- (void)clearIdPasswordCache
{
    [UserDefaults removeObjectForKey:@"myID"];
    [UserDefaults removeObjectForKey:@"Pwd"];
    emailField.text = @"";
    passField.text = @"";
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"clearSucceed", nil) activityAnimated:NO duration:1.2f];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 2)
    {
        static NSString *cellIndentifer = @"cellindentifier111";
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIndentifer];
        if(!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifer];
            cell.backgroundColor = [UIColor clearColor];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        
        UIView *b = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 70)];
        b.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:b];
        [b release];

        CGFloat w = [[NSString stringWithFormat:@"%@?",NSLocalizedString(@"forgetPassword", nil)] sizeWithFont:[UIFont systemFontOfSize:25] constrainedToSize:CGSizeMake(290, 70) lineBreakMode:kTextLineBreakByWordWrapping].width;
        UIButton *forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        forgetBtn.frame = CGRectMake(290-w, 0, w, 70);
//        forgetBtn.tag = 101
        forgetBtn.backgroundColor = [UIColor clearColor];
        [forgetBtn setTitle:[NSString stringWithFormat:@"%@?",NSLocalizedString(@"forgetPassword", nil)] forState:UIControlStateNormal];
        [forgetBtn setTitleColor: [UIColor blueColor] forState:UIControlStateNormal];
        forgetBtn.titleLabel.font = [UIFont systemFontOfSize:25];
        [forgetBtn addTarget:self action:@selector(resetPassword) forControlEvents:UIControlEventTouchUpInside];
        forgetBtn.titleLabel.textAlignment = kTextAlignmentRight;
        [b addSubview:forgetBtn];
        
//        UILabel *noticeLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 290,70)];
//        noticeLabel.tag = 101;
//        noticeLabel.numberOfLines = 0;
//        noticeLabel.backgroundColor = [UIColor whiteColor];
//        noticeLabel.text = [NSString stringWithFormat:@"%@?",NSLocalizedString(@"forgetPassword", nil)];
//        noticeLabel.textColor = [UIColor blueColor];
//        
//        noticeLabel.font = [UIFont systemFontOfSize:25];
//        noticeLabel.textAlignment = kTextAlignmentRight;
//        noticeLabel.backgroundColor = [UIColor clearColor];
//        [b addSubview:noticeLabel];
//        [noticeLabel release];
        forthCell = cell;
        forthView = b;
        return cell;
    }
    else
    {
        static NSString *cellIndentifer = @"cellindentifier";
        BanBu_RegisterCell *cell = (BanBu_RegisterCell *)[tableView dequeueReusableCellWithIdentifier:cellIndentifer];
        if(!cell)
        {
            cell = [[BanBu_RegisterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifer];
            cell.delegate = self;
            cell.backgroundColor = [UIColor clearColor];
        }
        if(indexPath.row == 0)
        {
            cell.textField.placeholder = NSLocalizedString(@"emailLabel", nil);
            emailField = cell.textField;
            emailField.placeholder = NSLocalizedString(@"userPlabeholder", nil);
            if([UserDefaults valueForKey:@"myID"]){
                emailField.text = [UserDefaults valueForKey:@"myID"];
                
            }
        }
        else if(indexPath.row == 1)
        {
            cell.textField.placeholder = NSLocalizedString(@"errorMsg3", nil);
            cell.textField.text = [UserDefaults valueForKey:@"Pwd"];
            cell.textField.secureTextEntry = YES;
            passField = cell.textField;
//            [self cellTextFieldDidEditing:passField];
        }
        return cell;
    }
    
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self checkIfCanNext];
}
-(void)resetPassword
{
    BanBu_ForgetPWController *forgetPW = [[BanBu_ForgetPWController alloc] init];
    [self.navigationController pushViewController:forgetPW animated:YES];
    [forgetPW release];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    if(indexPath.row == 3)
    {
        [passField resignFirstResponder];
        [emailField resignFirstResponder];
    }

}

#pragma mark - 判断是否可以显示enter按钮
-(void)checkIfCanNext
{
    if(passField.text.length&&emailField.text.length&&!isReadyNext)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 320, 70);
        //        btn.backgroundColor = [UIColor redColor];
        [btn setBackgroundImage:[UIImage imageNamed:@"topbar.png"] forState:UIControlStateNormal];
        [btn setTitle:@"Enter" forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:25];
        [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [btn setContentEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(nextStep) forControlEvents:UIControlEventTouchUpInside];
        enterButton = btn;
        
        UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gonext.png"]];
        img.frame = CGRectMake(280, 22.5, 25, 25);
        [btn addSubview:img];
        goNext = img;
//        [img release];
        
        UIActivityIndicatorView *a = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        a.frame = CGRectMake(280, 22.5, 25, 25);
        [btn addSubview:a];
        a.hidden = YES;
        loading = a;
//        [a release];
        
        UIView *aview = [[UIView alloc] init];
        aview.backgroundColor = TABLECOLOR;
        aview.frame = CGRectMake(0, 0, 320, 70);
        
        [forthCell addSubview:btn];
        [forthCell addSubview:aview];
        
        forthView.hidden = YES;
        isReadyNext = YES;
        
            [UIView animateWithDuration:.3 animations:^{
            
            aview.frame = CGRectMake(320, 0,320, 70);
        } completion:^(BOOL finished) {
            [aview removeFromSuperview];
        }];
        [aview release];
    }
    else if((!passField.text.length||!emailField.text.length)&&isReadyNext)
    {
        UIView *aview = [[UIView alloc] init];
        aview.backgroundColor = TABLECOLOR;
        aview.frame = CGRectMake(320, 0, 320, 70);
        
        [forthCell addSubview:aview];
        
        
        isReadyNext = NO;
        
            [UIView animateWithDuration:.3 animations:^{
            aview.frame = CGRectMake(0, 0,320, 70);
        } completion:^(BOOL finished) {
            
            [enterButton removeFromSuperview],enterButton = nil;
            forthView.hidden = NO;
            [aview removeFromSuperview];
        }];
    }
}
- (void)cellTextFieldBeginEditing:(UITextField *)textField andCell:(BanBu_RegisterCell *)cell
{
    [self checkIfCanNext];

}
- (void)cellTextFieldDidEditing:(UITextField *)textField
{
    [self checkIfCanNext];
}
- (BOOL)cellTextField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(range.location>=16&&textField == passField)
    {
        return NO;
    }
    return YES;
}

#pragma mark -
#pragma mark - 输入账号密码，登陆程序
/**
 * @函数名称：nextStep
 * @函数描述：
 * @输入参数：
 * @输出参数：
 * @返回值：
 * @author：your name
 */
-(void)nextStep
{
    [passField resignFirstResponder];
    [emailField resignFirstResponder];
    if(passField.text.length<6)
    {
        NSString *errorMsg = NSLocalizedString(@"errorMsg3", nil);
        [self showError:errorMsg];
        [self setErrorCellIndex:1];
        return;
    }
    [self setEnterButtonLoading:YES];
    [self login:Nil];
}

#pragma mark - 登录
- (void)login:(UIButton *)button
{
    if(!emailField.text.length)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"userNameNil", nil) activityAnimated:NO duration:2.0];
        return;
    }
    if(passField.text.length<6)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"passWordError", nil) activityAnimated:NO duration:2.0];
        return;
    }
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:emailField.text,@"email",passField.text,@"pass",nil];
    
    [self loginRequest:dic];
    
    [MyAppDataManager initDetailChatMessageTable];
    
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    if([emailField isFirstResponder]){
        [emailField resignFirstResponder];
    }
    if([passField isFirstResponder]){
        [passField resignFirstResponder];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField.returnKeyType == UIReturnKeyGo)
    {
        [self performSelector:@selector(login:)];
    }
    return YES;
}


- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    NSLog(@"%@",resDic);
    [self setEnterButtonLoading:NO];
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0.0];
    if(error)
    {
        if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        
        return;
    }
    
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Check_Login])
    {
        [UserDefaults setValue:@"" forKey:@"QUser"];
        [UserDefaults setValue:@"" forKey:@"sinaUser"];
        [UserDefaults setValue:@"" forKey:@"FBUser"];
        [UserDefaults setValue:@"" forKey:@"TUser"];
        
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            [UserDefaults setValue:[NSNumber numberWithBool:NO] forKey:@"isDefaultKey"];//用户用的是默认密码
            [UserDefaults setValue:[NSNumber numberWithBool:NO] forKey:@"isNewRegister"];//新注册用户
            [UserDefaults setValue:[NSNumber numberWithBool:NO] forKey:@"isDefaultKey"];//用户用的是默认密码
            [UserDefaults setValue:passField.text forKey:@"Pwd"];//新注册用户
            if(![[resDic objectForKey:@"bindlist"] isEqual:@""])
            {
                //绑定信息
                NSString *bindString;
                NSArray *bindArray;
                
                for(int i=0;i<[[resDic objectForKey:@"bindlist"] count];i++)
                {
                    NSDictionary *bindDic= [[resDic objectForKey:@"bindlist"] objectAtIndex:i];
                    bindString = [bindDic objectForKey:@"bindstring"];
                    bindArray= [bindString componentsSeparatedByString:@","];
                    
                    if([[bindDic objectForKey:@"bindto"]isEqualToString:@"ten_weib"] && ![bindString isEqualToString:@""])
                    {
                        [UserDefaults setValue:[bindArray objectAtIndex:0] forKey:AppTokenKey];
                        [UserDefaults setValue:[bindArray objectAtIndex:1] forKey:AppTokenSecret];
                        [UserDefaults setValue:[bindArray objectAtIndex:2] forKey:@"QUser"];
                    }
                    
                    if([[bindDic objectForKey:@"bindto"]isEqualToString:@"sina_wei"]&& ![bindString isEqualToString:@""])
                    {
                        [UserDefaults setValue:[bindArray objectAtIndex:0] forKey:@"AccessToken"];
                        [UserDefaults setValue:[bindArray objectAtIndex:1] forKey:@"sinaUser"];
                    }
                    if([[bindDic objectForKey:@"bindto"]isEqualToString:@"facebook"]&& ![bindString isEqualToString:@""])
                    {
                        [UserDefaults setValue:[bindArray objectAtIndex:0] forKey:@"FBAccessToken"];
                        [UserDefaults setValue:[bindArray objectAtIndex:1] forKey:@"FBUser"];
                    }
                    if([[bindDic objectForKey:@"bindto"]isEqualToString:@"twitter"]&& ![bindString isEqualToString:@""])
                    {
                        [UserDefaults setValue:[bindArray objectAtIndex:0] forKey:@"TAccessToken"];
                        [UserDefaults setValue:[bindArray objectAtIndex:1] forKey:@"TAccessTokenSecret"];
                        [UserDefaults setValue:[bindArray objectAtIndex:2] forKey:@"TUser"];
                    }
                }
            }
            
            MyAppDataManager.loginid = [resDic valueForKey:@"loginid"];
            MyAppDataManager.useruid = [resDic valueForKey:@"userid"];
            MyAppDataManager.userAvatar =[resDic valueForKey:@"uface"];
            NSLog(@"%@",[UserDefaults valueForKey:MyAppDataManager.useruid]);
            if([UserDefaults valueForKey:MyAppDataManager.useruid]&&![[UserDefaults valueForKey:MyAppDataManager.useruid] isKindOfClass:[NSDictionary class]])
            {
                [UserDefaults setValue:[NSDictionary dictionary] forKey:MyAppDataManager.useruid];
            }
            //            [UserDefaults setValue:<#(id)#> forKey:MyAppDataManager.useruid];
            if(![[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"])
            {
                NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithCapacity:2];
                [settingsDic setValue:[NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES], nil] forKey:@"boolKey"];
                [settingsDic setValue:@"msg_1" forKey:@"MusicSwith"];
                [settingsDic setValue:@"send_0" forKey:@"sendMsgBoolKey"];//添加发消息声音提示
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"systemset_friendreadstatus"];//发送消息已读状态设置
                [settingsDic setValue:[NSNumber numberWithBool:NO] forKey:@"setFollowsHidden"];//隐藏关注的人，默认为否，不隐藏
                
                [settingsDic setValue:[resDic valueForKey:@"hideme"] forKey:@"hideme"];
                NSMutableDictionary *addDic = [NSMutableDictionary dictionaryWithDictionary:resDic];
                [addDic setValue:settingsDic forKey:@"settings"];
                [UserDefaults setValue:addDic forKey:MyAppDataManager.useruid];
            }
            else
            {
                NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithDictionary:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]];
                [settingsDic setValue:[resDic valueForKey:@"hideme"] forKey:@"hideme"];
                NSMutableDictionary *addDic = [NSMutableDictionary dictionaryWithDictionary:resDic];
                [addDic setValue:settingsDic forKey:@"settings"];
                [UserDefaults setValue:addDic forKey:MyAppDataManager.useruid];
            }
            
            BOOL bl = [BanBu_UpgradeDataBase backupDB];
            if (bl)
            {
                NSLog(@"数据库升级完成");
            }
            
            //添加三个系统通知设置
            if(![[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"] valueForKey:@"visitYouNotification"])
            {
                NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithDictionary:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]];
                
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"visitYouNotification"];   //接收“我查看了你的个人资料”通知
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"followYouNotification"];  //接收“我关注了你”通知
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"takeCareNotification"];   //接收新用户注册通知
                
                NSMutableDictionary *addDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
                [addDic setValue:settingsDic forKey:@"settings"];
                [UserDefaults setValue:addDic forKey:MyAppDataManager.useruid];
            }
            
            //是否删除聊天表
            if (![[[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"] valueForKey:@"onceRun"] boolValue])
            {
                //保存版本号
                NSString  *versonPath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"data.dat"];
                
                NSMutableDictionary * versonDic = [NSKeyedUnarchiver unarchiveObjectWithFile:versonPath];
                NSString * versonString = [versonDic valueForKey:MyAppDataManager.useruid];
                NSInteger versonNum = [versonString integerValue];
                
                //当前版本
                versonString = MyAppDataManager.newVersionNumber;
                versonString = [versonString stringByReplacingOccurrencesOfString:@"." withString:@""];
                
                NSInteger newVerson = [[MyAppDataManager.newVersionNumber stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
                
                if (newVerson > 100)
                {
                    newVerson /= 10;
                }
                if (versonNum > 100)
                {
                    versonNum /= 10;
                }
                
                if (versonNum < newVerson )//1.5.1 :15;1.6.1:16；如果1.6：16，1.6.1：16；两者相等，如果没有旧版本号，说明是新登录的，直接更新
                {
                    //1备份数据库（chat_130026_0 被分为chat_130026_0_bak,talkPeoples130026被分为talkPeoples130026_bak等等）
                    BOOL bl = [BanBu_UpgradeDataBase backupDB];
                    if (bl)
                    {
                        NSLog(@"数据库升级完成");
                    }
                }
                
                //保存当前本版号
                [versonDic setValue:versonString forKey:MyAppDataManager.useruid];
                NSData *listData=[NSKeyedArchiver archivedDataWithRootObject:versonDic];
                [listData writeToFile:versonPath atomically:YES];
                
                NSMutableDictionary * settingDic = [NSMutableDictionary dictionaryWithDictionary:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]];
                
                [settingDic setValue:[NSNumber numberWithBool:1] forKey:@"onceRun"];
                NSMutableDictionary * dic =[NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
                [dic setValue:settingDic forKey:@"settings"];
                
                [UserDefaults setValue:dic forKey:MyAppDataManager.useruid];
            }
            //创建10张聊天记录表
            [MyAppDataManager initDetailChatMessageTable];
            [UserDefaults setValue:MyAppDataManager.useruid forKey:@"myID"];
            
            [UserDefaults synchronize];
            [UserDefaults setValue:[resDic valueForKey:@"friendlist"] forKey:FriendShip];
            
#pragma mark - 登陆成功
            BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            delegate.logined = YES;
            [delegate setViewController:YES];
        }
        else
        {
//            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"userNameOrpassWordError", nil) activityAnimated:NO duration:2.0];
            if([[resDic allKeys] indexOfObject:@"error"] != NSNotFound)
            {
                UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"sysNotice", nil) message:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil),nil];
                alert.tag = 2;
                [alert show];
                [alert release];
            }


//            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title: activityAnimated:NO duration:2.0];
        }
    }

    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_accountbind])
    {
        NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
        [uidDic setValue:[resDic valueForKey:@"bindlist"] forKey:@"bindlist"];
        [UserDefaults setValue:uidDic forKey:MyAppDataManager.useruid];
        [UserDefaults synchronize];
        
        BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
        delegate.logined = YES;
        [delegate setViewController:YES];
    }
}

#pragma mark - 账号密码检验
/*//用户登录校验
 网址　http://www.koochat.com/_user_login/_check_user_login.php?jsonfrom=
 参数　{"fc":"check_user_login","email":"abcd123456@gmail.com","pass":"123456","plong":"118113314","plat":"40019923"}
 返回　{"fc":"check_user_login","logok":"y","loginid":"20120707212149-3E4227CB-2D3E-A6D5-A656-BA755B231D71","serveron":"127.0.0.1"}
 
 email值为用户邮箱，pass值为用户
 long值为经度, lat值为纬度
 logok值为y表示登录成功，值为n表示登录失败
 loginid值为登录ID，供后期调用时向服务器端提交此值
 serveron值为分配的服务器，部分接口功能需发送请求到该返回值指定的服务器*/

- (void)loginRequest:(NSDictionary *)_nameAndPassWd
{
    NSMutableDictionary *loginDic = [NSMutableDictionary dictionary];
    
    [loginDic addEntriesFromDictionary:_nameAndPassWd];
    
    [loginDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:@"plat"];
    [loginDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:@"plong"];
    [loginDic setValue:[UserDefaults valueForKey:@"pushid"] forKey:@"pushid"];
    NSString *isJailbroken = nil;
    if([[UIDevice currentDevice] isJailbroken]){
        isJailbroken = @"YES";
    }else{
        isJailbroken = @"NO";
    }
    NSError *error;
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFStringCreateCopy( NULL, uuidString);
    CFRelease(puuid);
    CFRelease(uuidString);
    if(![[SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error] length])
    {
        [SFHFKeychainUtils storeUsername:@"halfeet_user_UUID" andPassword:result forServiceName:@"com.halfeet_halfeet" updateExisting:YES error:&error];
    }
    
    NSString *systemUDID = [SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error];
    [loginDic setValue:[NSString stringWithFormat:@"%@::%@::%@::%@::%@::%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion],[MyAppDataManager getPreferredLanguage],[[UIDevice currentDevice] platformString],isJailbroken,systemUDID] forKey:@"sysparam"];
    //    NSLog(@"%@",[NSString stringWithFormat:@"%@::%@::%@::%@::%@::%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion],[MyAppDataManager getPreferredLanguage],[[UIDevice currentDevice] platformString],isJailbroken,systemUDID]);
    //    NSLog(@"%@",[[UIDevice currentDevice] platformString]);
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:[[UIDevice currentDevice] systemVersion] forKey:@"osver"];
    NSString *deviceStr = [[UIDevice currentDevice] platformString];
    NSString *dev = nil;
    NSString *isp = nil;
    if([deviceStr rangeOfString:@"("].location != NSNotFound&&[deviceStr rangeOfString:@")"].location != NSNotFound)
    {
        isp = [deviceStr substringFromIndex:[deviceStr rangeOfString:@"("].location];
        dev = [deviceStr substringToIndex:[deviceStr rangeOfString:@"("].location];
    }
    //    NSLog(@"%@ %@",isp,dev);
    [dic setValue:isp forKey:@"isp"];
    [dic setValue:dev forKey:@"dev"];
    
    [dic setValue:[[UIDevice currentDevice] name] forKey:@"name"];
    [dic setValue:isJailbroken forKey:@"jail"];
    [loginDic setValue:dic forKey:@"phoneinfor"];
    
    //yinlinlin 2014年08月08日15:24:12 先使用pushid，获取不到的情况下使用systemUDID
    BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
    
    if(ap.pushid&&ap.pushid.length)
    {
        [loginDic setValue:ap.pushid forKey:@"deviceid"];
    }
    else
    {
       
        [loginDic setValue:systemUDID forKey:@"deviceid"];
    }

    
    [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
    [loginDic setValue:version forKey:@"version"];
    [AppComManager getBanBuData:BanBu_Check_Login par:loginDic delegate:self];
    self.navigationController.view.userInteractionEnabled = NO;
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"loading", nil) activityAnimated:YES];
    
    //创建10张聊天记录表
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [AppComManager cancalHandlesForObject:self];
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0.0];
    
}

@end
